package org.qiancizhan.Mapper;

import org.qiancizhan.Config.MySQL;
import org.qiancizhan.Model.DTO.LoginDTO;
import org.qiancizhan.Model.POJO.UserPOJO;
import org.qiancizhan.Utils.MD5CryptoUtil;

import java.util.List;

public class UserMapper {
    private final MySQL mysql = MySQL.getInstance();
    public UserPOJO getUser(String username){
        List<UserPOJO> list = mysql.executeQuery("select * from users where username = '"+username+"'",rs -> {
            UserPOJO pojo = new UserPOJO();
            pojo.setId(rs.getInt("id"));
            pojo.setUsername(rs.getString("username"));
            pojo.setPassword(rs.getString("password"));
            pojo.setCreated_at(rs.getTimestamp("created_at"));
            pojo.setUpdated_at(rs.getTimestamp("updated_at"));
            return pojo;
        });
        return list.size() > 0 ? list.get(0) : null;
    }

    public boolean addUser(LoginDTO userData){
        return mysql.executeUpdate(
                "INSERT INTO users (username, password) VALUES (?, ?)",
                userData.getUsername(),
                MD5CryptoUtil.encrypt(userData.getPassword())
        ) > 0;
    }

}
